import Vue from "vue";
import VueRouter from "vue-router";
import PanelView from "@/views/PanelView.vue";
import LoginView from "@/views/LoginView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: LoginView,
  },
  {
    path: "/middle",
    component: () => import("@/views/MiddleView.vue"),
  },
  {
    path: "/platform",
    name: "platform",
    component: () => import("@/components/platformCom.vue"),
  },
  {
    path: "/panel",
    component: PanelView,
    name: "panel",
    meta: { requireAuth: true },
    redirect: "/panel/role",
    children: [
      {
        path: "role",
        name: "role",
        component: () => import("@/components/roleCom.vue"),
      },
      {
        path: "menu",
        name: "menu",
        component: () => import("@/components/menuCom.vue"),
      },
      {
        path: "resource",
        name: "resource",
        component: () => import("@/components/resourceCom.vue"),
      },
      {
        path: "user",
        component: () => import("@/components/userCom.vue"),
      },
      {
        path: "customer",
        name: "customer",
        component: () => import("@/components/customerCom.vue"),
      },
      {
        path: "returnvisit",
        name: "returnvisit",
        component: () => import("@/components/returnvisitCom.vue"),
      },
      {
        path: "sign",
        name: "sign",
        component: () => import("@/components/signCom.vue"),
      },
    ],
  },
  {
    path: "*",
    component: () => import("@/views/NotFound.vue"),
  },
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

router.beforeEach((to, from, next) => {
  //  如果一个路由下，有很多个子路由，这些子路由都需要进行登陆权限校验，此时可以将元信息挂载到当前路由上
  //  当访问子路由时，实际会匹配两个路由：一级路由和二级路由
  //  只要判断其中一个路由，是否需要登陆验证才能访问，如果存在，则需要验证

  // const requireAuth = to.matched.some(route => {
  //   return route.meta.requireAuth
  // })

  let requireAuth = false;
  //  matched：代表当前路由所在的路径，匹配到了哪几个路由规则
  to.matched.forEach((route) => {
    if (route.meta.requireAuth) {
      requireAuth = true;
    }
  });

  const token = localStorage.getItem("token");
  const startlogin = localStorage.getItem("startlogin");
  const exptime = localStorage.getItem("exptime");

  if (requireAuth) {
    if (token && +new Date() - startlogin < exptime) {
      next();
    } else {
      alert("请登陆后再操作");
      localStorage.clear();

      //  如果本身就在登陆页，就不需要再跳往登陆页了
      if (from.path !== "/") {
        //  当跳转时，将原本目标路由的路径(to.path)，作为参数传递到登陆页
        router.push("/?redirect=" + to.path);
      }
    }
  } else {
    next();
  }
});

export default router;
